package com.oig.sys.swagger.config;


import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import io.swagger.v3.oas.models.security.OAuthFlow;
import io.swagger.v3.oas.models.security.OAuthFlows;
import io.swagger.v3.oas.models.security.Scopes;
import io.swagger.v3.oas.models.security.SecurityScheme;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpHeaders;

@RequiredArgsConstructor
@ConditionalOnProperty(name = "swagger.enabled")
public class SwaggerAutoConfiguration {

    private final SwaggerProperties swaggerProperties ;

    @Bean
    public OpenAPI springOpenAPI() {
        OpenAPI openAPI = new OpenAPI()
                .info(new Info().title(swaggerProperties.getTitle()).description(swaggerProperties.getDescription())
                        .termsOfService(swaggerProperties.getTermsOfServiceUrl()).version(swaggerProperties.getVersion())
                        .license(new License().name(swaggerProperties.getLicense()).url(swaggerProperties.getLicenseUrl()))
                        .contact(new Contact().email(swaggerProperties.getContact().getEmail()).name(swaggerProperties.getContact().getName())
                                .url(swaggerProperties.getContact().getUrl())));
        //代码加@SchemaRequirement oauth
        if (swaggerProperties.getTokenUrl()!=null && !"".equals(swaggerProperties.getTokenUrl().trim())){
            openAPI.schemaRequirement(HttpHeaders.AUTHORIZATION, this.securityScheme());
        }
        return openAPI;
    }


    private SecurityScheme securityScheme() {
        OAuthFlow clientCredential = new OAuthFlow();
//        clientCredential.setAuthorizationUrl(swaggerProperties.getAuthorizationUrl());
        clientCredential.setTokenUrl(swaggerProperties.getTokenUrl());
        Scopes scopes = new Scopes() ;
        swaggerProperties.getScopes().forEach(s -> scopes.addString(s, null));
        clientCredential.setScopes(scopes);
        OAuthFlows oauthFlows = new OAuthFlows();
        oauthFlows.password(clientCredential);

//        oauthFlows.setAuthorizationCode(clientCredential);
        SecurityScheme securityScheme = new SecurityScheme();
        securityScheme.setType(SecurityScheme.Type.OAUTH2);
        securityScheme.setFlows(oauthFlows);
        return securityScheme;
    }


}
